package com.zxl.common.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.zxl.common.exception.BusinessException;
import com.zxl.common.mapper.SysSmsCodeMapper;
import com.zxl.common.model.SmsCfg;
import com.zxl.common.model.pojo.SysSmsCode;
import com.zxl.common.service.SysSmsCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zxw
 * @since 2023-04-05
 */
@Slf4j
@Service
public class SysSmsCodeServiceImpl extends ServiceImpl<SysSmsCodeMapper, SysSmsCode> implements SysSmsCodeService {

    @Resource
    private SmsCfg smsCfg;
    @Resource
    private SysSmsCodeMapper sysSmsCodeMapper;

    @Override
    public void send(String phone, Map<String, Object> param, String templateCode) {
        //创建远程连接客户端对象
        DefaultProfile profile = DefaultProfile.getProfile(
                smsCfg.getRegionId(),
                smsCfg.getKeyId(),
                smsCfg.getKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        //创建远程连接的请求参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", smsCfg.getRegionId());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", smsCfg.getSignName());
        request.putQueryParameter("TemplateCode", templateCode);
        Gson gson = new Gson();
        String json = gson.toJson(param);
        request.putQueryParameter("TemplateParam", json);


        try {
            //使用客户端对象携带请求对象发送请求并得到响应结果
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            HashMap<String, String> resultMap = gson.fromJson(data, HashMap.class);
            String code = resultMap.get("Code");
            String message = resultMap.get("Message");
            log.info("阿里云短信发送响应结果：");
            log.info("code：" + code);
            log.info("message：" + message);


        } catch (ServerException e) {
            log.error("阿里云短信发送SDK调用失败：");
            log.error("ErrorCode=" + e.getErrCode());
            log.error("ErrorMessage=" + e.getErrMsg());
            throw new BusinessException(e);
        } catch (ClientException e) {
            log.error("阿里云短信发送SDK调用失败：");
            log.error("ErrorCode=" + e.getErrCode());
            log.error("ErrorMessage=" + e.getErrMsg());
            throw new BusinessException(e);
        }

    }

    @Override
    public void check(String code, String phone, Integer codeType) {
        List<SysSmsCode> sysSmsCodes = sysSmsCodeMapper.selectList(new QueryWrapper<SysSmsCode>()
                .eq("phone_num", phone)
                .eq("code", code)
                .eq("code_type", codeType)
                .orderByDesc("id"));
        if (sysSmsCodes.size() <= 0){
            throw new BusinessException("验证码不存在");
        }
        if (sysSmsCodes.get(0).getEndTime() < System.currentTimeMillis()){
            throw new BusinessException("验证码已过期");
        }
        if (sysSmsCodes.get(0).getUsed()) {
            throw new BusinessException("已被使用，请重新获取");
        }
        SysSmsCode sysSmsCode = sysSmsCodes.get(0);
        sysSmsCode.setUsed(true);
        sysSmsCodeMapper.updateById(sysSmsCode);
    }

}
